package com.itheima.api.array.demo02;

public class QuickSortArrarDemo01 {

    public static void main(String[] args) {

        int[] arr = {9,8,6,1,4,5,7,3,2};
        quickSort(arr, 0, arr.length - 1);
        traverse(arr);


    }
    public static void traverse(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + ",");
        }
    }

    public static void quickSort(int[] arr, int minIndex, int maxIndex){
        if (minIndex < maxIndex){
            int partitionIndex = partition(arr, minIndex, maxIndex);
            quickSort(arr, minIndex, partitionIndex - 1);
            quickSort(arr, partitionIndex + 1, maxIndex);
        }
    }

    public static int partition(int[] arr, int minIndex, int maxIndex){

        int temp = arr[minIndex];
        while (minIndex < maxIndex) {
            while (minIndex < maxIndex && arr[maxIndex] >= temp) {
                maxIndex--;
            }
            if (minIndex < maxIndex) {
                arr[minIndex] = arr[maxIndex];
                minIndex++;
            }
            while (minIndex < maxIndex && arr[minIndex] < temp) {
                minIndex++;
            }
            if (minIndex < maxIndex) {
                arr[maxIndex] = arr[minIndex];
                maxIndex--;
            }
        }
        arr[maxIndex] = temp;
        return maxIndex;
    }
}
